package cn.itcast.hotel.service.impl;

import cn.itcast.hotel.mapper.HotelMapper;
import cn.itcast.hotel.pojo.Hotel;
import cn.itcast.hotel.pojo.HotelDoc;
import cn.itcast.hotel.pojo.PageResult;
import cn.itcast.hotel.pojo.RequestParams;
import cn.itcast.hotel.service.IHotelService;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders;
import org.elasticsearch.search.SearchHit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Service
public class HotelService extends ServiceImpl<HotelMapper, Hotel> implements IHotelService {
    @Autowired
    private RestHighLevelClient client;

    @Override
    public PageResult search(RequestParams params) {
        int page = params.getPage();
        int size = params.getSize();
        String key = params.getKey();
        SearchRequest request = new SearchRequest("hotel");
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();


        if (key == null || "".equals(key)) {
            boolQuery.must(QueryBuilders.matchAllQuery());
        }
        else {
            boolQuery.must(QueryBuilders.matchQuery("all", key));

        }
        if (params.getCity()!=null&&!params.getCity().equals("")){
            boolQuery.filter(QueryBuilders.termQuery("city",params.getCity()));
        }
        if (params.getBrand()!=null&&!params.getBrand().equals("")){
            boolQuery.filter(QueryBuilders.termQuery("brand",params.getBrand()));
        }
        if (params.getStarName()!=null&&!params.getStarName().equals("")){
            boolQuery.filter(QueryBuilders.termQuery("starName",params.getStarName()));
        }
        if (params.getMinPrice()!=null&&params.getMaxPrice()!=null){
           boolQuery.filter(QueryBuilders.rangeQuery("price")
                   .gte(params.getMinPrice()).
                           lte(params.getMaxPrice()));
        }
        request.source().query(boolQuery);
        request.source().from((page - 1) * size).size(size);

        FunctionScoreQueryBuilder functionScoreQuery= QueryBuilders.functionScoreQuery(boolQuery
                ,new FunctionScoreQueryBuilder.FilterFunctionBuilder[]{
                   new FunctionScoreQueryBuilder.FilterFunctionBuilder(
                           QueryBuilders.termQuery("isAD",true),
                           ScoreFunctionBuilders.weightFactorFunction(10)
                   )
                });
        request.source().query(functionScoreQuery);
        SearchResponse response = null;
        try {
            response = client.search(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        }
        Long totalHits = response.getHits().getTotalHits().value;

        SearchHit[] hits = response.getHits().getHits();
        List<HotelDoc> hotelA = new ArrayList();
        for (SearchHit hit : hits) {
            String sourceAsString = hit.getSourceAsString();
            HotelDoc hotel = JSON.parseObject(sourceAsString, HotelDoc.class);
            hotelA.add(hotel);
        }

        return new PageResult(totalHits, hotelA);
    }
}
